package com.fahai.web.controller;

import com.fahai.common.PageVo;
import com.fahai.utils.RequestUtil;
import com.fahai.utils.json.JsonResult;
import com.fahai.web.entity.*;
import com.fahai.web.service.AllConfigService;
import com.fahai.web.service.CallRecordService;
import com.fahai.web.service.LawyerInfoService;
import com.fahai.web.vo.CallFlownoVo;
import com.fahai.web.vo.LawyerInfoVo;
import com.fahai.web.vo.LawyerSkillVo;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 律师管理控制器
 */

@Controller
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequestMapping(value = "/lawyer")
public class LawyerManagerController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(LawyerManagerController.class);

    @Autowired
    LawyerInfoService lawyerInfoService;

    @Autowired
    CallRecordService callRecordService;

    @Autowired
    AllConfigService allConfigService;

    //PropertyPlaceholder.getProperty("webUrl");

    @Value("#{system.webUrl}")
    public String webUrl;



    /**
     * 跳转到律师管理的页面
     * @return
     * @throws IOException
     */
  //  @ApiOperation(value = "律师管理")
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0','律师管理-1')")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String listLawyerInfo(Model model) throws IOException {

        List<LawyerSkill> skills=lawyerInfoService.findSkillInfoList(11);

        List<Map<String,Object>> plats=lawyerInfoService.selectProductInfoList();

        List<Map<String,Object>>  advantage=lawyerInfoService.selectPersonAdvantage();

        model.addAttribute("skills",skills);

        model.addAttribute("plats",plats);

        model.addAttribute("selectTab","律师管理");


        model.addAttribute("advantage", advantage);
        return "lawyer_manager";
    }

    /**
     * 查询律师修改回填信息
     * @param
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0','律师管理-1')")
    @RequestMapping(value="/getLawyerList",method = RequestMethod.POST)
    public JsonResult getLawyerAll(PageVo pageVo, LawyerInfoVo lawyerInfoVo){


        if(lawyerInfoVo!=null){

            if(lawyerInfoVo.getCreateTimeBegin()!=null&&!"".equals(lawyerInfoVo.getCreateTimeBegin())){
                lawyerInfoVo.setCreateTimeBegin(lawyerInfoVo.getCreateTimeBegin()+" 00:00:00");
            }


            if(lawyerInfoVo.getCreateTimeEnd()!=null&&!"".equals(lawyerInfoVo.getCreateTimeEnd())){
                lawyerInfoVo.setCreateTimeEnd(lawyerInfoVo.getCreateTimeEnd()+" 23:59:59");
            }

        }

        pageVo = lawyerInfoService.findLawyerList(lawyerInfoVo,pageVo);

        return ok("查询律师列表",pageVo);
    }


    /**
     * (不是列表加载）
     * 输出查询条件时的查询结果
     * 省市县查询只匹配其中最精确的，如县的优先级大约市
     * @param lawyerInfoVo
     * @param pageVo
     * @param model
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0','律师管理-1')")
    @RequestMapping(value = "/queryLawyerInfo", method = RequestMethod.GET)
    public String queryLawyerInfo(LawyerInfoVo lawyerInfoVo, PageVo pageVo, Model model) throws IOException {
        pageVo = lawyerInfoService.findLawyerGroupInfo(lawyerInfoVo,pageVo);
        model.addAttribute("lawyerInfoVoList",pageVo.getResult());
        model.addAttribute("selectTab","律师管理");

        return "lawyer_manager";
    }

    /**
     * 查询律师修改回填信息
     * @param lawyerid
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value="/findLawyerInfoUpdate",method = RequestMethod.GET)
    public JsonResult findLawyerInfoNeedUpdate(@RequestParam Integer lawyerid){
        LawyerInfoVo lawyerInfoVo = lawyerInfoService.findLawyerInfoToUpdate(lawyerid);

        return ok("律师信息修改",lawyerInfoVo);
    }

    /**
     * 更新单个律师的简明信息
     * @param model
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value = "/updateLawyerInfo",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult updateLawyerInfo(@RequestParam LawyerInfoVo lawyerInfoVo, Model model){
        lawyerInfoService.updateLawyerInfo(lawyerInfoVo);
        return ok("修改成功");
    }

    /**
     * 删除律师社会荣誉
     * @param skillId
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value = "/deleteSocietyHonor",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult deleteLawyerSocietyHonor(@RequestParam Integer skillId){
        LawyerSkill lawyerSkill = new LawyerSkill();
        lawyerSkill.setSkillId(skillId);
        lawyerInfoService.deleteLawyerSocietyHonor(lawyerSkill);
        return ok("删除成功");
    }

    /**
     * 批量冻结账户
     * @param lawyerIdList
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value = "/frozeLawyerAccount", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult frozeLawyerAccount(@RequestParam(value = "lawyerIdList[]") Integer[] lawyerIdList ){
        List<LawyerInfo> lawyerInfoList = new ArrayList<>();

        for(Integer lawyerid:lawyerIdList){
            LawyerInfo lawyerInfo = new LawyerInfo();
            lawyerInfo.setLawyerid(lawyerid);
            lawyerInfo.setIsValid(2);
            lawyerInfoList.add(lawyerInfo);

            Map<String,Object> openIdValid=lawyerInfoService.selectOpenIdValid(lawyerid);

            RequestUtil.sendPost(webUrl,"type=V1&openId="+openIdValid.get("lawyer_wxopenid").toString());
        }
        lawyerInfoService.updateFrozeLawyerAccount(lawyerInfoList);

        return ok("冻结成功");
    }

    /**
     * 批量解冻账户
     * @param lawyerIdList
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value = "/releaseFrozeLawyer", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult releaseFrozeLawyer(@RequestParam(value = "lawyerIdList[]") Integer[] lawyerIdList ){
        List<LawyerInfo> lawyerInfoList = new ArrayList<>();

        for(Integer lawyerid:lawyerIdList){
            LawyerInfo lawyerInfo = new LawyerInfo();
            lawyerInfo.setLawyerid(lawyerid);
            lawyerInfo.setIsValid(1);
            lawyerInfoList.add(lawyerInfo);

            Map<String,Object> openIdValid=lawyerInfoService.selectOpenIdValid(lawyerid);

            RequestUtil.sendPost(webUrl,"type=V2&openId="+openIdValid.get("lawyer_wxopenid").toString());
        }
        lawyerInfoService.updateFrozeLawyerAccount(lawyerInfoList);
        return ok("解冻成功");
    }

    /**
     * 返回律师详情的信息
     * @param lawyerid
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0','律师管理-1')")
    @RequestMapping(value = "/findLawyerDetailInfo",method= RequestMethod.GET)
    public String findLawyerDetailInfo(@RequestParam Integer lawyerid, Model model){
        Map<String, Object> lawyerDetailInfo = lawyerInfoService.findLawyerDetailInfo(lawyerid);
        List<Map<String,Object>> plats=lawyerInfoService.selectProductInfoList();
        model.addAttribute("plats",plats);
        model.addAttribute("lawyerDetailInfo",lawyerDetailInfo);
        model.addAttribute("selectTab","律师管理");
//        return "lawyer_detail";
        return "lawyer_material";
    }


    /**
     * 返回律师详情的信息ajax请求
     * @param lawyerid
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0','律师管理-1')")
    @RequestMapping(value = "/findLawyerDetailInfoEdit",method= RequestMethod.POST)
    @ResponseBody
    public JsonResult findLawyerDetailInfoEdit(@RequestParam Integer lawyerid){
        Map<String, Object> lawyerDetailInfo = lawyerInfoService.findLawyerDetailInfo(lawyerid);

        return ok("律师信息修改",lawyerDetailInfo);
    }


    /**
     * 返回修改律师详情信息
     * @param lawyerInfo TODO 律师服务地区修改 待实现
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @ResponseBody
    @RequestMapping(value = "/updateLawyerDetailInfo",method= RequestMethod.GET)
    public JsonResult updateLawyerDetailInfo(@RequestParam LawyerInfo lawyerInfo ){
        lawyerInfoService.updateLawyerDetailInfo(lawyerInfo);

        return ok("修改成功");
    }

    /**
     * 修改律师技能
     * @param lawyerSkillVo
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value="/updateLawyerSkill",method = RequestMethod.GET)
    public JsonResult updateLawyerSkill(@RequestParam LawyerSkillVo lawyerSkillVo){
        lawyerInfoService.updateLawyerSkillInfo(lawyerSkillVo);
        return ok("修改成功");
    }


    /**
     * 修改律师下线
     * @param lawyerId
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value = "/updateOffline", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult updateOffline(@RequestParam Integer lawyerId ){

            LawyerInfo lawyerInfo = new LawyerInfo();
            lawyerInfo.setLawyerid(lawyerId);
            lawyerInfo.setLawyerStates(2);

        lawyerInfoService.updateLawyerOffline(lawyerInfo);
        return ok("下线成功");
    }


    /**
     * 修改律师上线
     * @param lawyerId
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value = "/updateOnline", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult updateOnline(@RequestParam Integer lawyerId ){

        LawyerInfo lawyerInfo = new LawyerInfo();
        lawyerInfo.setLawyerid(lawyerId);
        lawyerInfo.setLawyerStates(1);

        lawyerInfoService.updateLawyerOffline(lawyerInfo);
        return ok("上线成功");
    }


    /**
     *编辑修改律师详情信息
     * @param editPlates
     * @param
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value = "/updateLwayerInfo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult updateLwayerInfo(@RequestParam(value="editPlates[]",required=false)List<Integer> editPlates,@RequestParam(value="editPrefer[]",required=false)List<String> editPrefer,@RequestParam(value="editAdvantage[]",required=false)List<String> editAdvantage,@RequestParam(value="addHonor[]",required=false)List<String> addHonor, Integer lawyerId, Integer isValid,@RequestParam(value="editHonor",required=false)String editHonor) {

        //勾选的平台


        lawyerInfoService.updateLawyerPlat(editPlates,lawyerId);


        //勾选的擅长






          List<LawyerGroupSkill> lgss=new ArrayList<LawyerGroupSkill>();


          if(editPrefer!=null){

            for (String skillid:editPrefer) {

                LawyerGroupSkill lawyerGroupSkill=new LawyerGroupSkill();


                String[]idAndType=skillid.split("-");

                lawyerGroupSkill.setSkillId(Integer.parseInt(idAndType[0]));
                lawyerGroupSkill.setSkillType(Integer.parseInt(idAndType[1]));
                lawyerGroupSkill.setLawyerid(lawyerId);

                lgss.add(lawyerGroupSkill);


           }


              lawyerInfoService.deleteGroupSkill(lawyerId,11);

              lawyerInfoService.batchSaveLawyerGroupSkill(lgss);

          }






        //选择优势


            lawyerInfoService.deleteGroupSkill(lawyerId,21);
            lawyerInfoService.deleteGroupSkill(lawyerId,22);
            lawyerInfoService.deleteGroupSkill(lawyerId,23);

            List<LawyerGroupSkill> lgsList=new ArrayList<LawyerGroupSkill>();


            if(editAdvantage!=null){


                for (String skillid:editAdvantage) {



                    if(!"".equals(skillid)){

                        LawyerGroupSkill lawyerGroupSkill=new LawyerGroupSkill();


                        String[]idAndType=skillid.split("-");

                        lawyerGroupSkill.setSkillId(Integer.parseInt(idAndType[0]));
                        lawyerGroupSkill.setSkillType(Integer.parseInt(idAndType[1]));
                        lawyerGroupSkill.setLawyerid(lawyerId);

                        lgsList.add(lawyerGroupSkill);

                    }


                }

                if(lgsList.size()!=0){

                    lawyerInfoService.batchSaveLawyerGroupSkill(lgsList);


                }


            }






        //修改已经编辑过的社会荣耀
        if (editHonor != null && !("".equals(editHonor))) {

            Gson gson = new Gson();


            Map<String, String> result = gson.fromJson(editHonor, Map.class);

            List<LawyerSkill> lss=new ArrayList<LawyerSkill>();

            List<LawyerSkill> newLss=new ArrayList<LawyerSkill>();


            for (String key : result.keySet()) {

                String value = result.get(key);

                if(!"".equals(key)){

                    LawyerSkill ls=new LawyerSkill();

                    ls.setSkillId(Integer.parseInt(key));

                    ls.setSkillName(value);

                    lss.add(ls);

                }

            }

            if(lss.size()!=0){

                lawyerInfoService.batchUpdateLawyerSkill(lss);

            }



        }

        //保存新增的社会荣耀
        if (addHonor != null) {

            LawyerInfoVo liV=new LawyerInfoVo();

            liV.setHonorList(addHonor);

            liV.setLawyerid(lawyerId);

            lawyerInfoService.saveLawyerSocietyHonor(liV);

        }


        if(isValid!=null){


            Map<String,Object> openIdValid=lawyerInfoService.selectOpenIdValid(lawyerId);

            if(!openIdValid.get("is_valid").toString().equals("1")){


                        if(isValid==1){

                            RequestUtil.sendPost(webUrl,"type=VALID&openId="+openIdValid.get("lawyer_wxopenid").toString());


                        }


            }


            if(!openIdValid.get("is_valid").toString().equals("2")){


                if(isValid==2){


                    RequestUtil.sendPost(webUrl,"type=V1&openId="+openIdValid.get("lawyer_wxopenid").toString());

                }


            }


            //修改律师的状态
            LawyerInfo lawyerInfo=new LawyerInfo();

            lawyerInfo.setLawyerid(lawyerId);

            lawyerInfo.setIsValid(isValid);

            lawyerInfoService.updateLawyerValid(lawyerInfo);



        }


        return ok("编辑成功");

    }


    /**
     * 在详情中修改律师
     * @param lawyerInfo
     * @param editLawyer
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0')")
    @RequestMapping(value = "/updateLwayerInfoForInfo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult updateLwayerInfoForInfo(LawyerInfo lawyerInfo,@RequestParam(value="editLawyer",required=false)String editLawyer) {



        //编辑修改地址
        if (editLawyer != null && !("".equals(editLawyer))) {

            Gson gson = new Gson();

            Map<String, String> result = gson.fromJson(editLawyer, Map.class);

            List<LawyerCity> lcs=new ArrayList<LawyerCity>();

            for (String key : result.keySet()) {

                String value = result.get(key);

                if(!"".equals(key)){

                    LawyerCity lc=new LawyerCity();

                    lc.setCid(Integer.parseInt(key));
                    lc.setLawyerid(lawyerInfo.getLawyerid());
                    lc.setCname(value);
                    lcs.add(lc);

                }

            }

            LawyerCity newLawCity=new LawyerCity();

            newLawCity.setLawyerid(lawyerInfo.getLawyerid());

            lawyerInfoService.deleteLawyerCity(newLawCity);

            lawyerInfoService.batchSaveLawyerCity(lcs);

        }


        lawyerInfoService.updateLawyerValid(lawyerInfo);

        return ok("编辑成功");

    }


    /**
     * 打开通话记录
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0','律师管理-1')")
    @RequestMapping(value = "/findConverseList",method= RequestMethod.GET)
    public String findConverseList(@RequestParam("lawyerid")Integer lawyerId,Model model){
        AllConfig  allConfig=new AllConfig();
        allConfig.setConfEname("good_call");
        PageVo pageVo=new PageVo();
        pageVo=allConfigService.getAllConfigList(allConfig,new PageVo());
        List<AllConfig> configs=(List<AllConfig>) pageVo.getResult();
        if(null!=configs&&configs.size()>=1){
            String confValue=configs.get(0).getConfValue();
            model.addAttribute("confValue",confValue);
            model.addAttribute("lawyerId",lawyerId);
        }
        model.addAttribute("selectTab","律师管理");
        return "converse_list";
    }

    /**
     * 查找律师通话记录
     * @param callFlownoVo  todo 分页
     * @return
     */
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0','律师管理-1')")
    @RequestMapping(value = "/findLawyerRecordList",method = RequestMethod.GET)
    public JsonResult findLawyerCallRecordList(CallFlownoVo callFlownoVo, PageVo pageVo){
        if("未知".equals(callFlownoVo.getCallStatus())){
            callFlownoVo.setCallStatus(null);
        }
        pageVo = callRecordService.findCallFlowList2(callFlownoVo,pageVo);
        return ok("通话流程表",pageVo);
    }

    @ResponseBody
    @PreAuthorize("hasAnyAuthority('ADMIN','律师管理-0','律师管理-1')")
    @RequestMapping(value ="/exportExcel" ,method=RequestMethod.POST)
    public void exportExcel(HttpServletRequest request, HttpServletResponse resp, LawyerInfoVo lawyerInfoVo){
    System.out.println("1234");

    }






}
